import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  cartGetCartListService,
  cartInsertCartListService,
  cartDeleteCartListService,
  cartMergeCartListService,
  cartUpdateCartListService,
  cartUpdateCartListSelectedService
} from '@/api/cart'
import { useUserStore } from '@/stores'

export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()

    // 1. 定义state - cartList存储在本地的购物车数据，登录后要与接口数据合并
    const cartList: any = ref([])
    // 2. 定义action - addCart
    const addCart = async (goods: any) => {
      const { skuId, count } = goods
      if (userStore.isLogin) {
        console.log('已登录，添加购物车')
        await cartInsertCartListService({ skuId, count })
        updateCartList()
      } else {
        console.log('未登录，添加购物车')
        console.log('添加', goods)
        // 添加购物车操作
        // 已添加过 - count + 1
        // 没有添加过 - 直接push
        // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
        const item: any = cartList.value.find(
          (item: any) => goods.skuId === item?.skuId
        )
        if (item) {
          // 找到了
          item.count += goods.count
        } else {
          // 没找到
          cartList.value.push(goods)
        }
      }
    }
    // 3. 定义action - updateCartList从接口获取数据
    const updateCartList = async () => {
      const res = await cartGetCartListService()
      cartList.value = res.data.result
    }
    //计算购物车总数量
    const allCount = computed(() =>
      cartList.value.reduce((sum: any, item: any) => sum + item.count, 0)
    )
    //计算购物车总价
    const allPrice = computed(() =>
      cartList.value.reduce(
        (sum: any, item: any) => sum + item.count * item.price,
        0
      )
    )
    //删除购物车数据
    const delCart = async (skuId: any) => {
      if (userStore.isLogin) {
        await cartDeleteCartListService([skuId])
        updateCartList()
      } else {
        cartList.value = cartList.value.filter(
          (item: any) => item.skuId !== skuId
        )
      }
    }
    //单选/取消单选
    const singleCheck = (skuId: string, selected: boolean) => {
      const item = cartList.value.find((item: any) => item.skuId === skuId)
      item.selected = selected
    }
    //全选/取消全选
    const allCheck = (selected: boolean) => {
      cartList.value.forEach((item: any) => (item.selected = selected))
    }
    //计算是否全选
    const isAllCheck = computed(() =>
      cartList.value.every((item: any) => item.selected)
    )
    //计算已选商品数量
    const allSelected = computed(() => {
      return cartList.value
        .filter((item: any) => item.selected)
        .reduce((sum: any, item: any) => sum + item.count, 0)
    })
    //计算已选商品总价
    const allSelectedPrice = computed(() => {
      return cartList.value
        .filter((item: any) => item.selected)
        .reduce((sum: any, item: any) => sum + item.count * item.price, 0)
    })
    //登录后合并本地购物车数据
    const mergeLocalCartList = async () => {
      const localCartList = cartList.value.map((item: any) => ({
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }))
      await cartMergeCartListService(localCartList)
      updateCartList()
    }
    //购物车数据更新时，通知接口更新选中状态和数量
    const updateCart = async (skuId: string) => {
      if (userStore.isLogin) {
        const item = cartList.value.find((item: any) => item.skuId === skuId)
        await cartUpdateCartListService(skuId, item.selected, item.count)
      } else {
        return
      }
    }
    //清空购物车
    const clearCartList = () => {
      cartList.value = []
    }
    //通知接口更新全选/取消全选
    const updateAllSelected = () => {
      if (userStore.isLogin) {
        const ids = cartList.value.map((item: any) => item.skuId)
        cartUpdateCartListSelectedService({
          selected: isAllCheck.value,
          ids
        })
      } else {
        return
      }
    }
    return {
      cartList,
      addCart,
      allCount,
      allPrice,
      delCart,
      singleCheck,
      isAllCheck,
      allCheck,
      allSelected,
      allSelectedPrice,
      mergeLocalCartList,
      updateCart,
      clearCartList,
      updateCartList,
      updateAllSelected
    }
  },
  {
    persist: true
  }
)
